# -*- coding = utf-8
#@[Time] : 2021/3/29 22:23
#@Auther : xiahuaS
#@File : BDfy.py
#@Software : PyCharm

import requests
import execjs,re

class BDFY():
    def __init__(self):
        self.base_url = 'https://fanyi.baidu.com/?aldtype=16047'
        self.url = 'https://fanyi.baidu.com/v2transapi?from=en&to=zh'
        self.word = input('Word: ')
        headers = {
            'User-Agent' and 'Cookie'(BAIDUID)
        }
        self.headers = headers
        self.from_ = ''
        self.to_ = ''

    def get_sign(self,word):
        with open('bdfy.js','r') as f:
            jscode = f.read()
        sign = execjs.compile(jscode).call('e',word)
        return sign

    def get_token(self):
        resp = requests.get(self.base_url,headers = self.headers)
        html = resp.content.decode('utf8')
        token = re.findall(r"token: '(.*)',",html)
        return token

    def parse_word(self):

        if re.findall(r'A-Za-z',self.word) != None:
            self.from_ = 'en'
            self.to_ = 'zh'
        if re.findall(r'\u4e00-\u9fa5',self.word) !=None:
            self.from_ = 'zh'
            self.to_ = 'en'

        return self.from_,self.to_

    def request(self):
        sign = self.get_sign(self.word)
        token = self.get_token()
        form_,to_ = self.parse_word()

        data = {
            'from': form_,
            'to': to_,
            'query': self.word,
            'transtype': 'realtime',
            'simple_means_flag': 3,
            'sign': sign,
            'token': token[0],
            'domain': 'common'
        }

        response = requests.post(self.url, headers=self.headers, data=data)
        data = response.json()
        translation = data['trans_result']['data'][0]['dst']
        print('tsl:',translation)

BDFY().request()
